#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "reg.pb-c.h"
#include "lookup.pb-c.h"

void setnonblocking(int fd)
{
	int oldfl = fcntl(fd,F_GETFL);
	int newfl = oldfl | O_NONBLOCK;

	if(fcntl(fd,F_SETFL,newfl) == -1)
	{
		perror("fcntl error\n");
	}
}



int create_socket(int port,const char *ip)
{
	int sock = 0,sockfd = 0;
	int ret = 0;
	struct sockaddr_in addr;

	memset(&addr,0,sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = inet_addr(ip);

	sock = socket(AF_INET,SOCK_STREAM,0);
	if(sock == -1)
	{
		perror("socket");
		exit(-1);
	}

	ret = bind(sock,(struct sockaddr *)&addr,sizeof(struct sockaddr));
	if(ret == -1)
	{
		perror("bind");
		exit(-1);
	}

	ret = listen(sock,5);
	if(ret == -1)
	{
		perror("listen");
		exit(-1);
	}

	return sock;
}

int main()
{

	int sock = 0;
	int sockfd = 0;
	char buf[100] = {0};
	int ret = 0;

	sock = create_socket(6868,"192.168.0.151");
	struct sockaddr_in cliaddr;
	memset(&cliaddr,0,sizeof(cliaddr));
	int len = sizeof(struct sockaddr);

	sockfd = accept(sock,(struct sockaddr *)&cliaddr,&len);
	if(sockfd == -1)
	{
		perror("accept");
		exit(-1);
	}

	Info *p = NULL;
	Find *q = NULL;
	
	while(1)
    {

		ret = recv(sockfd,buf,100,0);
		if(ret == -1)
		{
			perror("recv");
			exit(-1);
		}
		if(ret == 0)
		{
			close(sockfd);
			break;
		}

		printf("ret = %d\n",ret);
		if(memcmp(buf,"regi",4) == 0)
		{
			p = info__unpack(NULL,ret - 4,buf + 4);
			printf("register\n");
			printf("name is %s,passwd is %s\n",p->name,p->passwd);
			info__free_unpacked(p,NULL);
		}else if(memcmp(buf,"logi",4) == 0)
		{
			p = info__unpack(NULL,ret - 4,buf + 4);
			printf("login\n");
			printf("name is %s,passwd is %s\n",p->name,p->passwd);
			info__free_unpacked(p,NULL);
		}else if(memcmp(buf,"look",4) == 0)
		{
			q = find__unpack(NULL,ret - 4,buf + 4);
			printf("find by time\n");
			printf("time:%d %d %d\n",q->year,q->month,q->day);
			find__free_unpacked(q,NULL);
		}
	}


	close(sock);

	return 0;
}

